/**
 * 原生node.js接收前台post请求数据
 * @Author:Ghost
 * @Date:2016/07/14
 * @description:
 * 1、引入http,querystring（字符串解析）模块
 * 2、创建http服务器，监听3000端口
 * 3、判断路由是否为post和请求类型是否为post,如果是则进入请求接收处理
 * 4、声明变量alldata 存储接收到的数据
 * 5、绑定http请求的data事件，接收存储数据字符串
 * 6、绑定http请求的end事件，处理接收到的数据字符串，转换为对象
 * 7、输出
 */

//引入模块
var http = require('http');
var querystring = require('querystring');

const Sequelize = require('sequelize');
const config = require('./config');

// 第一步，创建一个sequelize对象实例：
var sequelize = new Sequelize(config.database, config.username, config.password, {
    host: config.host,
    dialect: 'mysql',
    pool: {
        max: 5,
        min: 0,
        idle: 30000
    }
});

// 第二步，定义模型Pet，告诉Sequelize如何映射数据库表：
var Pet = sequelize.define('pet', {
    id: {
        type: Sequelize.STRING(50),
        primaryKey: true
    },
    name: Sequelize.STRING(100),
    gender: Sequelize.BOOLEAN,
    birth: Sequelize.STRING(10),
    createdAt: Sequelize.BIGINT,
    updatedAt: Sequelize.BIGINT,
    version: Sequelize.BIGINT
}, {
    timestamps: false
});



//创建服务器
var server = http.createServer(function (req, res) {
    if (req.url === '/post' && req.method.toLowerCase() === 'post') {
        var alldata = '';
        req.on('data', function (chunk) {
            alldata += chunk;
        });

        req.on('end', function () {
            // res.end('success_success');
            //将字符串转换位一个对象
            // console.log(alldata); //username=%E6%9D%8E%E5%9B%9B&sex=%E5%A5%B3&hobby=%E7%9D%A1%E8%A7%89&hobby=%E6%89%93%E8%B1%86%E8%B1%86
            var dataString = alldata.toString();
            //将接收到的字符串转换位为json对象
            var dataObj = querystring.parse(dataString);
            //输出数据
            // 插入数据库
            var now = Date.now();
            Pet.create({
                id: now,
                name: dataObj.username,
                gender: false,
                birth: '2007-07-07',
                createdAt: now,
                updatedAt: now,
                version: 0
            }).then(function (p) {
                // JSON.stringify(p)
                res.end(JSON.stringify(dataObj));

                console.log(JSON.stringify(p));
            }).catch(function (err) {
                res.end(JSON.stringify('error'));

                console.log('failed: ' + err);
            });
            // console.log(dataObj);  //{ username: '王五', sex: '男', hobby: [ '吃饭', '睡觉', '打豆豆' ] }
            // console.log(dataObj.username); //王五
            // console.log(dataObj.sex); //男
            // console.log(dataObj.hobby); //[ '吃饭', '睡觉', '打豆豆' ]
        });
    };

});
//设置监听端口
server.listen(3000, "127.0.0.1", function () {
    console.log("server is started listen port 3000");
});
